package greedy;

/**
 * @Author: 海琳琦
 * @Date: 2022/2/27 21:54
 * https://leetcode-cn.com/problems/gas-station/
 */
public class CanCompleteCircuit {

    /**
     * 局部最优：当前累加rest[j]的和curSum一旦小于0，起始位置至少要是j+1，因为从j开始一定不行。
     * 全局最优：找到可以跑一圈的起始位置。
     * @param gas
     * @param cost
     * @return
     */
    public static int canCompleteCircuit(int[] gas, int[] cost) {
        int cur = 0;
        int total = 0;
        int start= 0;
        for (int i = 0; i < gas.length; i++) {
            cur += gas[i] - cost[i];
            total += gas[i] - cost[i];
            if (cur < 0) {
                start = i + 1;
                cur = 0;
            }
        }
        if (total < 0) {
            return -1;
        }
        return start;
    }

    public static void main(String[] args) {
        int[] a = {1, 2, 3, 4, 5};
        int[] b = {3, 4, 5, 1, 2};
        int i = canCompleteCircuit(a, b);
        System.out.println();
    }
}
